<template>
  <div class="container">
    <el-row :gutter="24" v-loading="loading">
      <!-- 左侧：用户信息 -->
      <el-col :span="8" class="user-info">
        <el-card shadow="hover">
          <el-form ref="formRef" :model="userInfo" label-position="top" :rules="rules">
            <el-form-item prop="avatar">
              <div class="avatar-container">
                <el-avatar :size="100" :src="userInfo.avatar" @click="uploadAvatar" class="avatar-image">
                  <el-icon><UserFilled /></el-icon>
                </el-avatar>
                <div class="avatar-overlay" @click="uploadAvatar">
                  <el-icon><Camera /></el-icon>
                  <span>更换头像</span>
                </div>
              </div>
            </el-form-item>

            <!-- 用户基本信息 -->
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userInfo.username" disabled>
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="姓名" prop="name">
              <el-input v-model="userInfo.name" clearable>
                <template #prefix>
                  <el-icon><UserFilled /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input type="email" v-model="userInfo.email" clearable>
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" clearable :autosize="{ minRows: 3, maxRows: 6 }" v-model="userInfo.remark" placeholder="请输入个人简介" />
            </el-form-item>

            <el-form-item>
              <el-button icon="CircleCheck" type="primary" @click="updateUserInfo" :loading="updating" class="update-btn"> 更新个人信息 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：安全设置 -->
      <el-col :span="16">
        <el-card shadow="hover" class="security-card">
          <template #header>
            <div class="security-header">
              <h3>账号安全</h3>
              <el-tag :type="securityLevel === 'high' ? 'success' : securityLevel === 'medium' ? 'warning' : 'danger'" effect="dark">
                {{ securityLevel === 'high' ? '安全级别高' : securityLevel === 'medium' ? '安全级别中' : '安全级别低' }}
              </el-tag>
            </div>
          </template>

          <div class="security-items">
            <!-- 密码修改 -->
            <div class="security-item">
              <div class="security-item-info">
                <el-icon><Lock /></el-icon>
                <div class="security-item-text">
                  <h4>登录密码</h4>
                  <p>建议您定期更换密码，设置安全性高的密码可以使账号更安全</p>
                </div>
              </div>
              <modifyPassword ref="passwordRef" @success="onPasswordChanged" />
            </div>

            <!-- 邮箱验证 -->
            <div class="security-item">
              <div class="security-item-info">
                <el-icon><Message /></el-icon>
                <div class="security-item-text">
                  <h4>邮箱验证</h4>
                  <p>已绑定邮箱：{{ userInfo.email || '未绑定' }}</p>
                </div>
              </div>
              <el-button type="primary" link @click="handleEmailVerify">
                {{ userInfo.email ? '修改' : '绑定' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 头像裁剪组件 -->
    <BaseCropper title="上传头像" ref="cropperRef" @confirm="setAvatar" />
  </div>
</template>

<script setup>
  import { useUserApi } from '@/api/user-api.js';
  import { RStatus } from '@/common/comstants.js';
  import modifyPassword from './components/ModifyPassword.vue';
  import { useUserStore } from '@/store/user-store.js';
  import BaseCropper from '@/components/BaseCropper.vue';

  // 用户信息
  const userInfo = ref({});
  // 加载状态
  const loading = ref(false);
  // 更新状态
  const updating = ref(false);
  // 头像裁剪组件
  const cropperRef = ref();
  // 表单
  const formRef = ref();
  // 修改密码组件
  const passwordRef = ref();

  // 表单验证规则
  const rules = reactive({
    username: [
      { required: true, message: '请输入用户名称', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    ],
    name: [
      { required: true, message: '请输入名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    ],
  });

  // 计算安全级别
  const securityLevel = computed(() => {
    let score = 0;
    if (userInfo.value.email) score++;
    if (userInfo.value.phone) score++;
    if (userInfo.value.password?.length >= 8) score++;
    return score >= 3 ? 'high' : score >= 2 ? 'medium' : 'low';
  });

  onMounted(() => {
    getUserInfo();
  });

  /** 获取用户信息 */
  const getUserInfo = async () => {
    loading.value = true;
    try {
      const res = await useUserApi().getUserInfo();
      if (res.status === RStatus.SUCCESS) {
        userInfo.value = res.data;
        useUserStore().userInfo = res.data;
      }
    } finally {
      loading.value = false;
    }
  };

  /** 更新用户信息 */
  const updateUserInfo = async () => {
    if (!formRef.value) return;
    await formRef.value.validate(async (valid) => {
      if (valid) {
        updating.value = true;
        try {
          const res = await useUserApi().updateUser(userInfo.value);
          if (res.status === RStatus.SUCCESS) {
            ElMessage.success('个人信息更新成功');
            getUserInfo();
          }
        } finally {
          updating.value = false;
        }
      }
    });
  };

  /** 上传头像 */
  const uploadAvatar = () => {
    cropperRef.value.open();
  };

  /** 设置头像 */
  const setAvatar = async (avatarBase64) => {
    userInfo.value.avatar = avatarBase64;
    const res = await useUserApi().updateUser(userInfo.value);
    if (res.status === RStatus.SUCCESS) {
      ElMessage.success('头像更新成功');
      getUserInfo();
    }
  };

  /** 处理邮箱验证 */
  const handleEmailVerify = () => {
    ElMessage.warning('邮箱验证功能暂未开放');
  };

  /** 密码修改成功回调 */
  const onPasswordChanged = () => {
    passwordRef.value.closeDialog();
  };
</script>

<style lang="scss" scoped>
  .container {
    padding: 24px;
    background-color: var(--el-bg-color-page);
    min-height: 100%;

    .user-info {
      .avatar-container {
        position: relative;
        width: 120px;
        height: 120px;
        margin: 0 auto 32px;
        cursor: pointer;

        .avatar-image {
          width: 100%;
          height: 100%;
          border: 3px solid var(--el-color-primary-light-7);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          transition: all 0.3s ease;

          &:hover {
            border-color: var(--el-color-primary);
            transform: scale(1.02);
          }
        }

        .avatar-overlay {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.6);
          border-radius: 50%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          opacity: 0;
          transition: all 0.3s ease;
          backdrop-filter: blur(2px);

          .el-icon {
            font-size: 28px;
            margin-bottom: 8px;
            color: white;
          }

          span {
            font-size: 14px;
            color: white;
            font-weight: 500;
          }

          &:hover {
            opacity: 1;
          }
        }
      }
    }

    .security-card {
      height: 100%;

      .security-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }

        .el-tag {
          padding: 6px 12px;
          border-radius: 6px;
          font-weight: 500;
        }
      }

      .security-items {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }

      .security-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px;
        border-radius: 12px;
        background-color: var(--el-bg-color);
        transition: all 0.3s ease;
        border: 1px solid var(--el-border-color-lighter);

        &:hover {
          transform: translateX(4px);
          border-color: var(--el-color-primary-light-7);
          background-color: var(--el-color-primary-light-9);
        }

        .security-item-info {
          display: flex;
          align-items: center;
          gap: 20px;

          .el-icon {
            font-size: 38px;
            padding: 12px;
            border-radius: 12px;
            color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-9);
          }

          .security-item-text {
            h4 {
              margin: 0 0 6px 0;
              font-size: 16px;
              font-weight: 600;
              color: var(--el-text-color-primary);
            }

            p {
              margin: 0;
              color: var(--el-text-color-secondary);
              font-size: 13px;
              line-height: 1.5;
            }
          }
        }

        :deep(.el-button) {
          font-size: 14px;
          font-weight: 500;
          padding: 8px 16px;
          border-radius: 6px;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-1px);
          }
        }
      }
    }
  }

  // 响应式布局优化
  @media screen and (max-width: 1200px) {
    .container {
      .el-col {
        width: 100%;
        margin-bottom: 24px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
</style>
@/store/user@/api/user-api@/store/user-store